package com.atguigu.gulimall.cart.interceptor;

import com.alibaba.nacos.api.config.filter.IFilterConfig;
import com.atguigu.common.constant.AuthServiceConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.cart.to.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 拦截器
 */
@Controller
public class CartInterceptor implements HandlerInterceptor {


    /**
     * ThreadLocal：每个线程都会维护一个自己的存储ThreadLocal的Map。
     * 可以向ThreadLocal中存放任何数据，只要是同线程下，就可以用ThreadLocal共享数据
     */
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 业务执行前
     * 在执行目标controller方法前，判断用户的登录状态，并封装到ThreadLocal中
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServiceConstant.LOGINUSER);
        if (member != null) {
            //用户已登录，则保存用户id
            userInfoTo.setUserId(member.getId());
        }


        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //如果有临时用户cookie，则保存临时用户信息
                if (cookie.getName().equals(CartConstant.TEMP_USER_COOKIE_NAME)) {
                    userInfoTo.setUserKey(cookie.getValue());
                    break;
                }
            }
        }
        if (StringUtils.isEmpty(userInfoTo.getUserKey())) {
            //如果没有临时用户cookie，则手动创建一个
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
            userInfoTo.setTempUser(true);
        }
        //将登录信息放入ThreadLocal，方便同线程共享
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行后
     * 分配临时用户，让浏览器保存
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        UserInfoTo userInfoTo = threadLocal.get();
        if (userInfoTo.isTempUser()) {
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
